var SF_QUICKBLOG = {
	lastUrl : null,
	prefs : null,
	
	myblogs : [],
	currentBlog : null,
	currentPostObject : { },
	postTitle : null,
	
	iframe : null,
	
	load : function () {
		SCRIBEFIRE_DB.load();
		
		var appcontent = document.getElementById("appcontent");
		
		if (appcontent) {
			appcontent.addEventListener("DOMContentLoaded", SF_QUICKBLOG.contentChange, false);
			appcontent.addEventListener("select", SF_QUICKBLOG.contentChange, false);
		}
		
		addEventListener("unload", SF_QUICKBLOG.unload, false);
		
		this.prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService)
			.getBranch("performancing.");
		
		
		this.loadMyBlogs();
		
		document.getElementById("scribefire-toolbar").hidden = false;
	},
	
	unload : function () {
		var appcontent = document.getElementById("appcontent");
		
		appcontent.removeEventListener("DOMContentLoadded", SF_QUICKBLOG.contentChange, false);
		appcontent.removeEventListener("select", SF_QUICKBLOG.contentChange, false);
	},
	
	loadMyBlogs : function () {
		var db = SCRIBEFIRE_DB.getDB();
		
		var select = db.createStatement("SELECT url FROM "+SCRIBEFIRE_DB.blogsTable);
		
		try {
			while (select.executeStep()) {
				this.myblogs.push(select.getUTF8String(0));
			}
		} catch (e) {
			alert(e);
		} finally {
			select.reset();
		}
		
		SCRIBEFIRE_DB.closeDB(db);
	},
	
	contentChange : function () {
		SF_QUICKBLOG.doContentChange();
	},
	
	multiprompt : function (text, value) {
		var re = [];
		
		window.openDialog("chrome://scribefire/content/quickblogging/mprompt.xul", "mprompt", "chrome,modal,centerscreen,resizable=no", re, text, value);
		
		if (re[0]) {
			return re[0];
		}

		return false;
	},
	
	doContentChange : function () {
		if (!content || content.document.location.href == this.lastUrl) return;
		
		this.lastUrl = content.document.location.href;
		
		if (this.prefs.getBoolPref("disableQuickblogging") || !this.isMyBlog(this.lastUrl)) {
			document.getElementById("scribefire-toolbar").collapsed = true;
		}
		else {
			document.getElementById("scribefire-toolbar").collapsed = false;
		}
	},
	
	isMyBlog : function (url) {
		for (var i = 0; i < this.myblogs.length; i++) {
			if (url.replace(/www\./i, "").indexOf(this.myblogs[i].replace(/www\./i, "")) == 0) {
				this.currentBlog = this.myblogs[i];
				return true;
			}
		}
		
		return false;
	},
	
	cancelAddImage : function () {
		// Remove any listeners already set (from double-clicking the button or whatever)
		try { content.document.removeEventListener("click", scribefireClick, false); } catch (noWorries) { }
	},
	
	addElement : function (type) {
		function cancel() {
			try { content.document.removeEventListener("mouseover", scribefireMOver, false); } catch (noWorries) { }
			try { content.document.removeEventListener("mouseout", scribefireMOut, false); } catch (noWorries) { }
			try { content.document.removeEventListener("click", scribefireClick, true); } catch (noWorries) { }
		}
		
		try {
			// Add the notification about clicking on the blog post.
			var nb = document.getElementById("content").getNotificationBox();
			nb.removeAllNotifications();
		
			nb.appendNotification(performancingUI.getLocaleString("qb.clickOnTitle"), type+"-notification", 'chrome://browser/skin/Info.png', 3, [ { accessKey : "V", callback : cancel, label : performancingUI.getLocaleString("cancel"), popup : null } ]);
		} catch (seamonkey) {
			alert(performancingUI.getLocaleString("qb.clickOnTitle"));
		}
		
		function scribefireMOver(event) {
			var node = event.originalTarget;
			
			node.oldBackgroundColor = node.style.backgroundColor;
			
			node.style.backgroundColor = "#ff0";
		}
		
		function scribefireMOut(event) {
			var node = event.originalTarget;
			
			node.style.backgroundColor = node.oldBackgroundColor;
		}
		
		function scribefireClick(event) {
			try { document.getElementById("content").getNotificationBox().removeAllNotifications(); } catch (seamonkey) { }
			
			scribefireMOut( { originalTarget : event.originalTarget });
			
			try { content.document.removeEventListener("mouseover", scribefireMOver, false); } catch (noWorries) { }
			try { content.document.removeEventListener("mouseout", scribefireMOut, false); } catch (noWorries) { }
			
			var hNode = event.originalTarget;
			var titleText = hNode.innerHTML.replace(/<[^>]+>/g, "").replace(/&nbsp;/g, " ").replace(/^\s+|\s+$/g, "");
			
			event.stopPropagation();
			event.preventDefault();
			
			content.document.removeEventListener("click", scribefireClick, true);
			
			if (!hNode) {
				alert(performancingUI.getLocaleString("qb.parsePostsError"));
				return;
			}
			
			var sf = document.getElementById('perFormancingMidasFrame').contentWindow;
			
			// Calls back to continueAddingCode
			SF_QUICKBLOG.getPost(SF_QUICKBLOG.currentBlog, titleText, type);
		}
		
		// Remove any listeners already set (from double-clicking the button or whatever)
		try { content.document.removeEventListener("click", scribefireClick, true); } catch (noWorries) { }
		try { content.document.removeEventListener("mouseover", scribefireMOver, false); } catch (noWorries) { }
		try { content.document.removeEventListener("mouseout", scribefireMOut, false); } catch (noWorries) { }
		
		content.document.addEventListener("click", scribefireClick, true);
		content.document.addEventListener("mouseover", scribefireMOver, false);
		content.document.addEventListener("mouseout", scribefireMOut, false);
	},
		
	getPost : function (blogUrl, title, type) {
		SF_QUICKBLOG.isBusy(true);
		
		this.postTitle = title;
		
		this.setupServiceObject(blogUrl);
		var xmlRequest = SCRIBEFIRE_BLOG.serviceObject.getRecentPosts(20, true, type);
		
		if (typeof xmlRequest != 'undefined') {
			// Shouldn't execute for Blogger
		    var theCall = new PffXmlHttpReq(SCRIBEFIRE_BLOG.api, "POST", xmlRequest, false, null, null);

		    theCall.onResult = function( aText, aXML ){
		        SF_QUICKBLOG.processRecentPosts(theCall.request.responseText, false, type);
		    };
	
		    theCall.onError = function (aStatusMsg, Msg) {
		    };
		
		    theCall.prepCall();
		    theCall.request.setRequestHeader("Content-Type", "text/xml");
		    theCall.makeCall();
		}
	},
	
	setupServiceObject : function (blogUrl) {
		var db = SCRIBEFIRE_DB.getDB();

		var select = db.createStatement("SELECT guid FROM "+SCRIBEFIRE_DB.blogsTable+" WHERE url=?1 LIMIT 1");
		select.bindUTF8StringParameter(0, blogUrl);
		
		try {
			while (select.executeStep()) {
				var guid = select.getString(0);
			}
		} catch (e) {
			SFLOG(e);
		} finally {
			select.reset();
		}
		
		SCRIBEFIRE_DB.closeDB(db);
		
		SCRIBEFIRE_BLOG.guid = guid;
	},
	
	processRecentPosts : function (responseText, alreadyParsed, type) {
		var theObject = null;
		
		if (alreadyParsed) {
			// Blogger
			theObject = responseText;
		}
		else {
			var re = /(\<\?\xml[0-9A-Za-z\D]*\?\>)/;
			var newstr = responseText.replace(re, "");
		
			var e4xXMLObject = new XML(newstr);
		
			if (e4xXMLObject.params.param.value.length() == 1) {
				theObject = bfXMLRPC.XMLToObject(e4xXMLObject.params.param.value.children()[0]);
			}
		}
		
		for (k = 0; k < theObject.length; k++){
			/* Begin mostly for LiveJournal */
			
			if (theObject[k].content) theObject[k].description = theObject[k].content;
			if (!theObject[k].title) theObject[k].title = "";
			
			try {
				var ljTitle = null;
				if (ljTitle = theObject[k].description.match(/<title>([^<]*)<\/title>/i)[1]) {
					theObject[k].title = ljTitle;
				}
			} catch (e) {
			}
			
			/* End mostly for LiveJournal */
			
			if (theObject[k].title.toString().replace(/&nbsp;/g, " ") == SF_QUICKBLOG.postTitle) {
				SF_QUICKBLOG.continueAddingCode(theObject[k], type);
				return;
			}
		}
		
		alert(performancingUI.getLocaleString("qb.parsePostsError"));
	},
	
	continueAddingCode : function (postObject, type) {
		SF_QUICKBLOG.currentPostObect = { };
		
		for (var i in postObject) {
			SF_QUICKBLOG.currentPostObject[i] = postObject[i];
		}
		
		SF_QUICKBLOG.isBusy(false);
		
		if (type == 'image') {
			window.openDialog("chrome://scribefire/content/quickblogging/add_from_flickr.xul", "add_from_flickr", "chrome,resizable=yes,centerscreen");
		}
		else if (type == 'video') {
			window.openDialog("chrome://scribefire/content/quickblogging/add_from_youtube.xul", "add_from_youtube", "chrome,resizable=yes,centerscreen");
		}
		else if (type == 'link') {
			var localeString = performancingUI.getLocaleString('midaseenterurl');
			var checkString = performancingUI.getLocaleString('openinnewwindow');
			var prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
			           	.getService(Components.interfaces.nsIPromptService);

			var input = { value: "http://" };
			var check = { value: false };

			var okorcancel = prompts.prompt(window, localeString, localeString, input, checkString, check);

			if (okorcancel) {
				SF_QUICKBLOG.finishAddLink(input.value, check.value);
			}
		}
		else if (type == 'picture') {
			var imageToInsert = performancingUI.openImageUpload();
			
			if (imageToInsert) {
				SF_QUICKBLOG.continueWithCode(type, '<img src="'+imageToInsert+'" />');
			}
		}
		else if (type == 'quote') {
			var quoteText = SF_QUICKBLOG.multiprompt(performancingUI.getLocaleString("quotePrompt"));
			
			if (quoteText) {
				quoteText = quoteText.replace(/^\s*|\s*$/g, "").replace(/\n/g, "<br />");
				
				SF_QUICKBLOG.continueWithCode(type, '<blockquote>'+quoteText+'</blockquote>');
			}
		}
	},
	
	finishAddLink : function (linkUrl, newWindow) {
		SF_QUICKBLOG.addLinkToPost(linkUrl, newWindow);
	},
		
	addLinkToPost : function (linkUrl, newWindow) {
		function cancel() {
			try { content.document.removeEventListener("mouseup", selectedText, true); } catch (noWorries) { }
		}
		
		try {
			var nb = document.getElementById("content").getNotificationBox();
			nb.removeAllNotifications();
			nb.appendNotification(performancingUI.getLocaleString("qb.selectForLink"), "link-notification", 'chrome://browser/skin/Info.png', 3, [ { accessKey : "V", callback : cancel, label : performancingUI.getLocaleString("cancel"), popup : null } ]);
		} catch (seamonkey) {
			alert(performancingUI.getLocaleString("qb.selectForLink"));
		}

		function selectedText(event) {
			try { document.getElementById("content").getNotificationBox().removeAllNotifications(); } catch (seamonkey) { }
			
			var sel = content.getSelection().toString();
			
			event.stopPropagation();
			event.preventDefault();
			content.document.removeEventListener("mouseup", selectedText, true);
			
			// Find the first occurence of sel that isn't in an HTML attribute.
			var oldText = SF_QUICKBLOG.currentPostObject.description;
			
			var newText = oldText;
			
			for (var i = 0; i < oldText.length; i++) {
				if (oldText.charAt(i) == '<') {
					i = oldText.indexOf(">", i);
				}
				else if (oldText.indexOf(sel, i) == i) {
					oldTextParts = [ oldText.substring(0, i), oldText.substring(i, i + sel.length), oldText.substring(i + sel.length) ];
					
					newText = oldTextParts[0] + '<a href="'+linkUrl+'"';
					if (newWindow) newText += ' target="_blank"';
					newText += '>' + oldTextParts[1] + "</a>" + oldTextParts[2];
					break;
				}
			}
			
			if (oldText == newText) {
				// Go with a more iffy route.
				
				// Replace any tags in the selection, along with any leading/trailing whitespace
				sel.replace(/<[^>]+>/g, "").replace(/^\s+|\s+$/, "");
				
				// Find the first occurence of the first 4 characters of the selection.
				var s1 = sel.substring(0, 4);
				
				// And the next occurrence of the last 3 characters.
				var s2 = sel.substring(sel.length - 3);
				
				var textParts = [null, null, null];
				var startReplace = oldText.indexOf(s1);
				
				if (startReplace > -1) {
					var endReplace = oldText.indexOf(s2, startReplace);
					
					if (endReplace > -1 && (endReplace >= startReplace)) {
						endReplace += s2.length;
						
						textParts[0] = newText.substring(0, startReplace);
						textParts[1] = newText.substring(startReplace, endReplace);
						textParts[2] = newText.substring(endReplace);
						
						newText = textParts[0] + '<a href="' + linkUrl +'"';
						if (newWindow) newText += ' target="_blank"';
						newText += '>' + textParts[1] + '</a>';
						newText += textParts[2];
					}
				}
			}
			
			if (oldText == newText) {
				alert(performancingUI.getLocaleString("qb.selectTextError"));
			}
			else {
				SF_QUICKBLOG.convertTextToHTML(newText, SF_QUICKBLOG.editPost);
			}
		}

		content.document.addEventListener("mouseup", selectedText, true);
	},
	
	continueWithCode : function (type, code, imgSrc) {
		SF_QUICKBLOG.doContinueWithCode(type, code, imgSrc);
	},
	
	convertTextToHTML : function (htmlText, callback) {
		var Cc = Components.classes;
		var Ci = Components.interfaces;
		
		// Taken from http://mxr.mozilla.org/seamonkey/source/browser/components/microsummaries/src/nsMicrosummaryService.js#2116
		var windowMediator = Cc['@mozilla.org/appshell/window-mediator;1'].
								getService(Ci.nsIWindowMediator);
		var window = windowMediator.getMostRecentWindow("navigator:browser");
		var document = window.document;
		var rootElement = document.documentElement;

		// Create an iframe, make it hidden, and secure it against untrusted content.
		SF_QUICKBLOG.iframe = document.createElement('iframe');
		SF_QUICKBLOG.iframe.setAttribute("collapsed", true);
		SF_QUICKBLOG.iframe.setAttribute("type", "content");

		// Insert the iframe into the window, creating the doc shell.
		rootElement.appendChild(SF_QUICKBLOG.iframe);

		// When we insert the iframe into the window, it immediately starts loading
		// about:blank, which we don't need and could even hurt us (for example
		// by triggering bugs like bug 344305), so cancel that load.
		var webNav = SF_QUICKBLOG.iframe.docShell.QueryInterface(Ci.nsIWebNavigation);
		webNav.stop(Ci.nsIWebNavigation.STOP_NETWORK);

		// Turn off JavaScript and auth dialogs for security and other things
		// to reduce network load.
		SF_QUICKBLOG.iframe.docShell.allowJavascript = false;
		SF_QUICKBLOG.iframe.docShell.allowAuth = false;
		SF_QUICKBLOG.iframe.docShell.allowPlugins = false;
		SF_QUICKBLOG.iframe.docShell.allowMetaRedirects = false;
		SF_QUICKBLOG.iframe.docShell.allowSubframes = false;
		SF_QUICKBLOG.iframe.docShell.allowImages = false;

		var parseHandler = {
			_self: this,

			handleEvent: function (event) {
				event.target.removeEventListener("DOMContentLoaded", this, false);
				try     { callback(SF_QUICKBLOG.iframe.contentDocument.wrappedJSObject.body.innerHTML); }
				finally { this._self = null; SF_QUICKBLOG.iframe.parentNode.removeChild(SF_QUICKBLOG.iframe);SF_QUICKBLOG.iframe = null; }
			}
		};

		// Convert the HTML text into an input stream.
		var converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"].
		createInstance(Ci.nsIScriptableUnicodeConverter);
		converter.charset = "UTF-8";
		var stream = converter.convertToInputStream(htmlText);

		var uri = Components.classes['@mozilla.org/network/io-service;1'].getService(Components.interfaces.nsIIOService).newURI(content.document.location.href, null, null);

		// Set up a channel to load the input stream.
		var channel = Cc["@mozilla.org/network/input-stream-channel;1"].
		createInstance(Ci.nsIInputStreamChannel);
		channel.setURI(uri);
		channel.contentStream = stream;

		// Load in the background so we don't trigger web progress listeners.
		var request = channel.QueryInterface(Ci.nsIRequest);
		request.loadFlags |= Ci.nsIRequest.LOAD_BACKGROUND;

		// Specify the content type since we're not loading content from a server,
		// so it won't get specified for us, and if we don't specify it ourselves,
		// then Firefox will prompt the user to download content of "unknown type".
		var baseChannel = channel.QueryInterface(Ci.nsIChannel);
		baseChannel.contentType = "text/html";

		// Load as UTF-8, which it'll always be, because XMLHttpRequest converts
		// the text (i.e. XMLHTTPRequest.responseText) from its original charset
		// to UTF-16, then the string input stream component converts it to UTF-8.
		baseChannel.contentCharset = "UTF-8";

		// Register the parse handler as a load event listener and start the load.
		// Listen for "DOMContentLoaded" instead of "load" because background loads
		// don't fire "load" events.
		SF_QUICKBLOG.iframe.addEventListener("DOMContentLoaded", parseHandler, true);
		var uriLoader = Cc["@mozilla.org/uriloader;1"].getService(Ci.nsIURILoader);
		uriLoader.openURI(channel, true, SF_QUICKBLOG.iframe.docShell);
	},
	
	doContinueWithCode : function (type, code, imgSrc) {
		var postObject = this.currentPostObject;
		
		try {
			var headCode = content.document.getElementsByTagName("head")[0].innerHTML;
		} catch (e) {
			var headCode = '';
		}
		
		switch (type) {
			case 'picture':
			case 'quote':
				window.openDialog("chrome://scribefire/content/quickblogging/add_other_to_post.xul", "add_to_post", "chrome,resizable=yes,centerscreen", headCode, postObject.description, code);
			break;
			default:
				window.openDialog("chrome://scribefire/content/quickblogging/add_"+type+"_to_post.xul", "add_to_post", "chrome,resizable=yes,centerscreen", headCode, postObject.description, code, imgSrc);
			break;
		}
	},
	
	editPost : function (postCode){
		SF_QUICKBLOG.isBusy(true);
		
		var blogUrl = SF_QUICKBLOG.currentBlog;
		var postObject = SF_QUICKBLOG.currentPostObject;
		postObject.description = postCode;
		
		SF_QUICKBLOG.setupServiceObject(blogUrl);
		
		if (!postObject.postid) postObject.postid = postObject.postId;
		
		// Do the & stuff here.
		postObject.description = postObject.description.replace(/&amp;/g, '&');
		postObject.description = postObject.description.replace(/&/g, '&amp;');
		
		if (postObject.description.match(/<pre[^>]*>/i)) {
			try {
				var toReplace = postObject.description.match(/<pre[^>]*>([\s\S]+)<\/pre>/im)[1];
				var replaced = toReplace.replace(/</g, "&lt;");
				replaced = replaced.replace(/>/g, "&gt;");
				postObject.description = postObject.description.replace(toReplace, replaced);
			} catch (e) {
			}
		}
		
		var xmlRequest = SCRIBEFIRE_BLOG.serviceObject.editPost(postObject.postid, postObject.title, postObject.description, postObject.categories, "", 1, postObject.mt_keywords, null, true);
		
		if (typeof xmlRequest != 'undefined') {
			performancing_xmlcall.sendCommand(SCRIBEFIRE_BLOG.api, xmlRequest, null, null, null, function (v) { SF_QUICKBLOG.processPostEdit(v); });
		}
	},
	
	processPostEdit : function (responseText) {
		content.document.location.reload();
		SF_QUICKBLOG.isBusy(false);
	},
	
	isBusy : function (busy) {
		if (!busy) busy = false;
		
		document.getElementById("scribefire-od-button").setAttribute("busy", busy.toString());
	}
};

addEventListener("load", function () { SF_QUICKBLOG.load(); }, false);